#include "tutorialWeightSystematics.hxx"
#include "AnalysisUtils.hxx"
#include "BasicUtils.hxx"

//********************************************************************
tutorialWeightSystematics::tutorialWeightSystematics():SystematicWeightBase(2){
  //********************************************************************
  Int_t baseindex=0;
  _scintmass= SystematicSource("FGD1Mass",      SystematicSource::k1D_SYMMETRIC);
  baseindex+=_scintmass.GetNBins();
  _watermass = SystematicSource("FGD2MassWater",SystematicSource::k1D_SYMMETRIC);
  baseindex+=_watermass.GetNBins();
  SetNParameters(baseindex);
 
 
}

//********************************************************************
Float_t tutorialWeightSystematics::Apply(const ToyVariations& toy, SystBoxB& box, const AnaEventB& event){
//********************************************************************
  Float_t eventWeight=1;
  bool dofgd1Ana=anaUtils::IsFGD1Analysis(event);
  bool dofgd2Ana=anaUtils::IsFGD2Analysis(event);
  if(!dofgd1Ana && !dofgd2Ana) return eventWeight;
  //  std::cout<<" DO FGD1 only ana? "<<dofgd1Ana<<std::endl;
  
  if (!box.TrueVertex) return eventWeight;         // True vertex associated to the recon vertex should exist
  
  // Get the fgdmass correction values for this run period 
  if( dofgd1Ana ){
    // if the true vertex is not inside the FGD1 it should not be scaled
    if (!anaUtils::InDetVolume(SubDetId::kFGD1, box.TrueVertex->Position)) return eventWeight;
    if(!_scintmass.GetParametersForBin(0, _scintmass_corr, _scintmass_err)) return eventWeight;
    // Compute the weight
    eventWeight= 1 + _scintmass_corr + _scintmass_err*toy.Variations[0];
  }
  if(dofgd2Ana){
    if ( !anaUtils::InDetVolume(SubDetId::kFGD2, box.TrueVertex->Position)) return eventWeight;
    // if the true vertex is in water:
    if (anaUtils::GetMaterialInFgd2( box.TrueVertex->Position)==2){
      if(!_watermass.GetParametersForBin(0, _watermass_corr, _watermass_err)) return eventWeight;
      eventWeight= 1 + _watermass_corr + _watermass_err*toy.Variations[1];
    }
    else{
      if(!_watermass.GetParametersForBin(0, _watermass_corr, _watermass_err)) return eventWeight;
      eventWeight= 1 + _scintmass_corr + _scintmass_err*toy.Variations[0];
    }
  }
  return eventWeight;
}

